package com.irdstudio.efp.esb.api.service.basicfn;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.efp.esb.api.bean.basicfn.req.RecRscWarnLoanReqBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceHandler;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.riskm.service.facade.RscWarnLoanService;
import com.irdstudio.efp.riskm.service.vo.RscWarnLoanVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 需求编号：【】（业务提的需求编号）
 * 问题编号：【】（若不是因为修复问题而新增该类，则留空）
 * 开发人员：【】
 * 创建日期：【2019-11-19 11:24】
 * 功能描述：
 */
@Service("recRscWarnLoanService")
public class RecRscWarnLoanService implements FrameworkService {

    public EsbRespServiceBean handleWithDatas(RecRscWarnLoanReqBean recRscWarnLoanReqBean, EsbReqServiceBean esbReqServiceBean) throws ESBException {
        try {
            //查询要修改的数据
            logger.info("查询要修改的数据开始，查询条件为：" + JSONObject.toJSONString(recRscWarnLoanReqBean));
            RscWarnLoanVO exitRscWarnLoan = getData2update(recRscWarnLoanReqBean);
            logger.info("查询要修改的数据结果为：" + JSONObject.toJSONString(exitRscWarnLoan));
            //检查返回的信息的关键字段是否和历史显存数据一致
            boolean flag = checkData(exitRscWarnLoan,recRscWarnLoanReqBean);
            //根据结果处理数据
            handleDatas(flag,recRscWarnLoanReqBean);
            return EsbRespServiceHandler.esbSuccessHandler(esbReqServiceBean);
        } catch (ESBException e) {
            throw new ESBException(e.getErrorCode(), e.getMessage());
        }
    }

    private void handleDatas(boolean flag, RecRscWarnLoanReqBean recRscWarnLoanReqBean) throws ESBException {
        if (flag) {
            logger.info("开始清空表中现存命中信息！");
            //清空表中现存信息
            deleteAllUserinfo(recRscWarnLoanReqBean.getDblNo(),recRscWarnLoanReqBean.getCustNo());
            if (StringUtil.isNullorBank(recRscWarnLoanReqBean.getRuleId()) || StringUtil.isNullorBank(recRscWarnLoanReqBean.getRuleNm())) {
                //组装未命中数据
                RscWarnLoanVO rscWarnLoanVo = assembleData(recRscWarnLoanReqBean);
                logger.info("组装得到的数据：" + JSONObject.toJSONString(rscWarnLoanVo));
                //执行更新操作（实际上是清空旧数据，重新插入新数据）
                updateRscData(rscWarnLoanVo);
            } else {
                //组装命中数据
                List<RscWarnLoanVO> rscWarnLoanList = assembleDataList(recRscWarnLoanReqBean);
                logger.info("组装得到的数据：" + JSONObject.toJSONString(rscWarnLoanList));
                //批量更新风险预警台账信息（实际上是清空旧数据，重新批量插入新数据）
                batchInsertRscData(rscWarnLoanList);
            }
        } else {
            logger.info("检查返回的信息的关键字段和历史显存数据不一致，故不做任何数据的处理！");
        }
    }

    private void batchInsertRscData(List<RscWarnLoanVO> rscWarnLoanList) {
        logger.info("开始批量执行更新！");
        int num = 0;
        num = rscWarnLoanService.batchInsertRscData(rscWarnLoanList);
        if (num < 0)
            logger.error("批量更新风险预警台账信息失败！");
        else
            logger.info("批量数据更新成功！");
    }

    private void deleteAllUserinfo(String dblNo, String custNo) {
        logger.info("清空表中现存命中信息！");
        int num = 0;
        num = rscWarnLoanService.deleteAllUserinfo(dblNo,custNo);
        if (num < 0)
            logger.error("清空表中现存命中信息失败！");
        else
            logger.info("清空表中现存命中信息完成！");
    }

    private void updateRscData(RscWarnLoanVO rscWarnLoanVO) throws ESBException {
        logger.info("开始执行更新！");
        int num = 0;
        num = rscWarnLoanService.insertRscWarnLoan(rscWarnLoanVO);
        if (num < 0)
            logger.error("更新风险预警台账信息失败！");
        else
            logger.info("数据更新成功！");
    }

    private boolean checkData(RscWarnLoanVO exitRscWarnLoan, RecRscWarnLoanReqBean recRscWarnLoanReqBean) {
        boolean flag = true;
        if (Objects.nonNull(exitRscWarnLoan)) {
            if (!exitRscWarnLoan.getBillNo().equals(recRscWarnLoanReqBean.getDblNo())) {
                logger.info("检查返回的信息的借据号和历史数据借据号不一致");
                flag = false;
            }
        } else {
            logger.info("查询到的历史数据为空");
            flag = false;
        }
        return flag;
    }

    private RscWarnLoanVO getData2update(RecRscWarnLoanReqBean recRscWarnLoanReqBean) {
        RscWarnLoanVO queryOldRs = new RscWarnLoanVO();
        try {
            RscWarnLoanVO rscWarnLoanVO = new RscWarnLoanVO();
            rscWarnLoanVO.setCusId(recRscWarnLoanReqBean.getCustNo());
            rscWarnLoanVO.setCusName(recRscWarnLoanReqBean.getCustNm());
            rscWarnLoanVO.setCertType(recRscWarnLoanReqBean.getIdentTp());
            rscWarnLoanVO.setCertCode(recRscWarnLoanReqBean.getIdentNo());
            rscWarnLoanVO.setBillNo(recRscWarnLoanReqBean.getDblNo());
            queryOldRs = rscWarnLoanService.queryByCond(rscWarnLoanVO);
            logger.info("查询到的历史数据为：" + JSONObject.toJSONString(queryOldRs));
            if (Objects.isNull(queryOldRs)) logger.info("查询历史数据结果为空！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return queryOldRs;
    }

    private List<RscWarnLoanVO> assembleDataList(RecRscWarnLoanReqBean recRscWarnLoanReqBean) {
        logger.info("组装批量数据开始！");
        /**
         * 查询得到的规则编号和规则名都是用逗号分隔的字符串，并且是一一对应好的
         * 故只需先将字符串转化为数组，再在循环里一一赋值，将结果组合成一个新的集合
         *
         */
        List<RscWarnLoanVO> list = new ArrayList<>();
        String[] ruleCode = recRscWarnLoanReqBean.getRuleId().split(",");
        String[] ruleName = recRscWarnLoanReqBean.getRuleNm().split(",");
        String[] desc = recRscWarnLoanReqBean.getDesc().split(",");
        for (int i = 0; i < ruleCode.length; i++) {
            RscWarnLoanVO rscWarnLoanVo = new RscWarnLoanVO();
            rscWarnLoanVo = assembleData(recRscWarnLoanReqBean);
            rscWarnLoanVo.setRuleCode(ruleCode[i]);
            rscWarnLoanVo.setRuleName(ruleName[i]);
            rscWarnLoanVo.setDescContent(desc[i]);
            list.add(rscWarnLoanVo);
        }
        logger.info("组装批量数据结束！" + JSONObject.toJSONString(list));
        return list;
    }

    private RscWarnLoanVO assembleData(RecRscWarnLoanReqBean recRscWarnLoanReqBean) {
        logger.info("组装数据开始！");
        RscWarnLoanVO rscWarnLoanVo = new RscWarnLoanVO();
        rscWarnLoanVo.setTaskNo(recRscWarnLoanReqBean.getRqsIdmptntID());
        rscWarnLoanVo.setCusId(recRscWarnLoanReqBean.getCustNo());
        rscWarnLoanVo.setCusName(recRscWarnLoanReqBean.getCustNm());
        rscWarnLoanVo.setCertType(recRscWarnLoanReqBean.getIdentTp());
        rscWarnLoanVo.setCertCode(recRscWarnLoanReqBean.getIdentNo());
        rscWarnLoanVo.setContNo(recRscWarnLoanReqBean.getContrNo());
        rscWarnLoanVo.setBillNo(recRscWarnLoanReqBean.getDblNo());
        rscWarnLoanVo.setLoanBalance(recRscWarnLoanReqBean.getLoanBal() == null?BigDecimal.ZERO:BigDecimal.valueOf(recRscWarnLoanReqBean.getLoanBal()));
        rscWarnLoanVo.setLoanStartDate(recRscWarnLoanReqBean.getLoanStrtDt());
        rscWarnLoanVo.setLoanEndDate(recRscWarnLoanReqBean.getLoanEndDt());
        rscWarnLoanVo.setRuleSetCode(recRscWarnLoanReqBean.getRuleGrpId());
        rscWarnLoanVo.setRuleSetName(recRscWarnLoanReqBean.getRuleGrpNm());
        rscWarnLoanVo.setRuleCode(recRscWarnLoanReqBean.getRuleId());
        rscWarnLoanVo.setRuleName(recRscWarnLoanReqBean.getRuleNm());
        rscWarnLoanVo.setDescContent(recRscWarnLoanReqBean.getDesc());
        rscWarnLoanVo.setRiskLevel(recRscWarnLoanReqBean.getRskLvl());
        rscWarnLoanVo.setWarmSour(recRscWarnLoanReqBean.getCrnRskElyWrnSrc());
        rscWarnLoanVo.setWarmRuleSour(recRscWarnLoanReqBean.getCrnRskElyWrnRuleSrc());
        rscWarnLoanVo.setRiskDate(recRscWarnLoanReqBean.getCrnRskElyWrnGenrtDt());
        rscWarnLoanVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        logger.info("组装批量数据结束！" + JSONObject.toJSONString(rscWarnLoanVo));
        return rscWarnLoanVo;
    }

    //日志信息
    private static final Logger logger = LoggerFactory.getLogger(RecRscWarnLoanService.class);

    @Autowired
    @Qualifier("rscWarnLoanService")
    private RscWarnLoanService rscWarnLoanService;
}
